import { BasicColumn, FormSchema } from '@/components/Table'
import { h } from 'vue'
import { Switch } from 'ant-design-vue'
import { useMessage } from '@/hooks/web/useMessage'
import { startOrStopItem } from '@/api/sys/dict'

type CheckedType = boolean | string | number

export const columns: BasicColumn[] = [
  {
    title: '字典编码',
    dataIndex: 'itemCode',
  },
  {
    title: '字典名称',
    dataIndex: 'itemName',
  },
  {
    title: '字典状态',
    dataIndex: 'status',
    width: 120,
    customRender: ({ record }) => {
      if (!Reflect.has(record, 'pendingStatus')) {
        record.pendingStatus = false
      }
      return h(Switch, {
        checked: record.status === 1,
        checkedChildren: '启用',
        unCheckedChildren: '停用',
        loading: record.pendingStatus,
        onChange(checked: CheckedType) {
          record.pendingStatus = true
          const newStatus = checked ? 1 : 0
          const { createMessage } = useMessage()
          startOrStopItem({ ...record, status: newStatus })
            .then(() => {
              record.status = newStatus
              // createMessage.success(`已成功修改角色状态`);
            })
            .catch(() => {
              // createMessage.error('修改角色状态失败');
            })
            .finally(() => {
              record.pendingStatus = false
            })
        },
      })
    },
  },
  // {
  //   title: '字典状态',
  //   dataIndex: 'status',
  // },
  {
    title: '显示顺序',
    dataIndex: 'itemSort',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
]

export const searchFormSchema: FormSchema[] = [
  {
    field: 'itemCode',
    label: '字典编码',
    component: 'Input',
    colProps: { span: 6 },
  },
  {
    field: 'itemName',
    label: '字典名称',
    component: 'Input',
    colProps: { span: 6 },
  },
]

export const dictFormSchema: FormSchema[] = [
  {
    field: 'itemCode',
    label: '字典编码',
    component: 'Input',
    rules: [
      {
        required: true,
        message: '请输入字典编码',
      },
    ],
  },
  {
    field: 'itemName',
    label: '字典名称',
    component: 'Input',
    required: true,
  },
  {
    field: 'itemSort',
    label: '显示顺序',
    component: 'InputNumber',
    required: true,
    defaultValue: 0,
    componentProps: {
      min: 0,
    },
  },
  {
    label: '描述',
    field: 'description',
    component: 'Input',
  },
]

export const dictContentFormSchema: FormSchema[] = [
  {
    field: 'dictCode',
    label: '字典组编码',
    component: 'Input',
    rules: [
      {
        required: true,
        message: '请输入字典编码',
      },
    ],
  },
  {
    field: 'dictNameCopy',
    label: '字典组名称',
    component: 'Input',
    required: true,
  },
]
